<?php
/**
 * Created by PhpStorm.
 * User: liuhongchuan
 * Date: 2018/5/25
 * Time: 14:13
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;

class Vice extends AdminBase
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $auth_group=sp_get_auth_menu_3("10041017");
        $this->assign("menus",$auth_group);
        echo $this->fetch();
    }

    public function ajaxIndex()
    {
        $card_no = input("card_no");
        $main_card_no = input("main_card_no");
        $name = input("name/s");
        $mobile = input("mobile/d");
        $draw = input("draw",0) + 1;//请求时间
        $shop_id = sp_get_current_shop_id();
        $where = array(
            "i.shop_id" => $shop_id,
            "i.owner_type" => 5
        );
        if (!empty($card_no)) {
            $where["i.card_no"] = array("like", "%{$card_no}%");
        }
        if (!empty($name)) {
            $where["i.name"] = array("like", "%{$name}%");
        }
        if (!empty($mobile)) {
            $where["i.mobile"] = array("like", "%{$mobile}%");
        }
        if (!empty($main_card_no)) {
            $where["mi.card_no"] = array("like", "%{$main_card_no}%");
        }
        $total = db("interface")->alias('i')
            ->join('m_interface mi', 'mi.id = i.original_id', 'left')
            ->where($where)
            ->count(1);
        $list = db("interface")->alias('i')
            ->join('m_interface mi', 'mi.id = i.original_id', 'left')
            ->field('i.id, i.card_no, i.name, i.mobile, i.membership_type, i.in_varifycation, i.in_varifycation_type, mi.card_no as main_card_no')
            ->where($where)
            ->order($this->get_order())
            ->limit($this->get_limit())
            ->select();

        $this->ajax(array('pageData'=>$list, 'total'=>$total, "draw"=>$draw));
    }

    /**
     * 添加
     */
    public function add()
    {
        $shop_id = sp_get_current_shop_id();
        if (request()->isPost()) {
            $card_no = input("card_no");
            $main_interface_id = input("main_interface_id");
            $in_varifycation = input("in_varifycation");
            $in_varifycation_type = input("in_varifycation_type");
            $name = input("name/s");
            $mobile = input("mobile");
            if (empty($card_no)) {
                $this->ajax_error("卡号不能为空");
            }
            if (empty($main_interface_id)) {
                $this->ajax_error("绑定主卡不能为空");
            }
            if (empty($name)) {
                $this->ajax_error("姓名不能为空");
            }
            if (empty($mobile)) {
                $this->ajax_error("手机号不能为空");
            }
            if(!preg_match("/^1[3456789]\d{9}$/", $mobile)) {
                $this->ajax_error("手机号格式不正确");
            }
            $main_interface = db("interface")->where(array("id" => $main_interface_id, "shop_id" => $shop_id))->find();
            if (empty($main_interface)) {
                $this->ajax_error("主卡不存在");
            }
            $is_exist = db("Interface")->where(array("card_no" => $card_no, "shop_id" => $shop_id))->count(1);
            if ($is_exist > 0) {
                $this->ajax_error("卡号已经存在");
            }
            $member = array(
                "card_no"           => $card_no,
                "in_varifycation"   => $in_varifycation,
                "in_varifycation_type"   => $in_varifycation_type,
                "fingerprint"   => input("fingerprint"),
                "start_date"        => $main_interface['start_date'],
                "end_date"          => $main_interface['end_date'],
                "mobile"            => $mobile,
                "contract_id"       => $main_interface["contract_id"],
                "member_id"         => $main_interface["member_id"],
                "name"              => $name,
                "surplus_num"       => $main_interface["surplus_num"],
                "membership_type"   => $main_interface["membership_type"],
                "contract_status"   => $main_interface["contract_status"],
                "sliding_group_id"  => $main_interface["sliding_group_id"],
                "owner_type"        => 5,
                "is_original"       => 0,
                "original_id"       => $main_interface["id"],
                "doors_auth"        => $main_interface["doors_auth"],
                "shop_id"           => $shop_id,
            );
			
			if(!empty(input("fingerprint"))&&strlen(input("fingerprint"))>500){//指纹验证
			     $this->_model_down_record_save_update(array("shop_id" => $shop_id, "card_no" => $card_no, "type" => 1));
			}
			if(!empty(input("icon1"))&&strlen(input("icon1"))>10){//人脸验证
				 $this->_face_code_insertOrupdate(array(
						  							"card_no"=>$card_no,"face1"=>input("face1"),
						  							"icon1"=>input("icon1"),
						  							"shop_id"=>$shop_id,
						  							"name"=>$name,
						  							"mobile"=>$mobile,
						  							));
			}	
			action('OptLog/api_add',['member'=>$member,'icon'=>input("icon1")]);
            db("Interface")->insert($member);
            $this->ajax_success("成功");
        }else {
			echo $this->fetch();
        }
    }

    /**
     * 修改
     */
    function edit(){
        $shop_id = sp_get_current_shop_id();
        $id = input("id/d");
        $model = db("Interface")->where(array("id" => $id, "shop_id" => $shop_id))->find();
		$old_model=$model;
		$old_icon=db("FaceCode")->where("shop_id=$shop_id and card_no='".$model['card_no']."'")->value('icon1');
        if (request()->isPost()) {
            if (empty($model)) {
                $this->ajax_error("参数错误");
            }
            $in_varifycation = input("in_varifycation");
            $in_varifycation_type = input("in_varifycation_type");


            $model["in_varifycation"] = $in_varifycation;
			$model["in_varifycation_type"] = $in_varifycation_type;
			$model["fingerprint"] = input('fingerprint');
			$model["mobile"] = input('mobile');
			$model["name"] = input('name');
            if (!empty(input("fingerprint"))&&strlen(input("fingerprint"))>500) {//需要验证
               $this->_model_down_record_save_update(array("shop_id" => $shop_id, "card_no" => $model['card_no'], "type" => 1));
			}
			
			if(!empty(input("icon1"))&&strlen(input("icon1"))>10){//人脸验证
				 $this->_face_code_insertOrupdate(array(
                        "card_no"   => $model['card_no'],
                        "face1"     => input("face1"),
                        "icon1"     => input("icon1"),
                        "shop_id"   => $shop_id,
                        "name"=>input("name"),
                        "mobile"=>input("mobile")
                    ));
			}else{
				db("FaceCode")->where("shop_id=$shop_id and card_no='".$model['card_no']."'")->delete();
			}
			action('OptLog/api_edit',['member'=>$old_model,'icon'=>empty($old_icon)?"":$old_icon,'member1'=>$model,'icon1'=>input("icon1","")]);
            db("Interface")->update($model);
            return $this->ajax_success("成功");

        }else{
            if (empty($model)) {
                $this->ajax_tpl("参数错误");
            }
            $this->assign("model",$model);
            $facecode = db("FaceCode")->where(" shop_id=$shop_id and  card_no='".$model['card_no']."'")->find();
            if(empty($facecode)){
                $this->assign("is_bind_face",0);
                $facecode=array("face1"=>null,"icon1"=>null);
            }else{
                $this->assign("is_bind_face",1);
            }
            if(empty($model['fingerprint'])){
                $this->assign("is_bind_finger",0);
            }else{
                $this->assign("is_bind_finger",1);
            }

            $this->assign("facecode",$facecode);
            $this->assign("icons",$this->getIcons(explode(",", $facecode['icon1'])));
            
            echo $this->fetch();
        }
    }

    //删除卡
    public function delete(){
        $id = input("id/d");
        $shop_id = sp_get_current_shop_id();
        $interface = db("Interface")->where(array("id" => $id, "shop_id" => $shop_id))->find();
        if (empty($interface)) {
            $this->ajax_error("参数错误");
        }
		$old_icon=db("FaceCode")->where("shop_id=$shop_id and card_no='".$interface['card_no']."'")->value('icon1');
		action('OptLog/api_del',['member'=>$interface,'icon'=>empty($old_icon)?'':$old_icon]);
        db("FaceCode")->where(array("shop_id" => $shop_id, "card_no" => $interface["card_no"]))->delete();
        db("Interface")->where(array("id" => $id, "shop_id" => $shop_id))->delete();

        return $this->ajax_success("成功");
    }

    /**
     * 搜索会员
     */
    public function ajaxSearchOrder()
    {
        $shop_id = sp_get_current_shop_id();
        $search = input("search","");
        if (mb_strlen($search) < 5) {
            $this->ajax(array());
        }
        $where = array("shop_id" => $shop_id, "membership_type" => 2, "owner_type" => 1, "mobile|card_no" => array("like", "%{$search}%"));

        $list = db("interface")
            ->where($where)
            ->field("id, CONCAT(name, '--', mobile, \"--\", card_no) as text, card_no")
            ->select();
        $this->ajax($list);
    }

    /**
     * 模板是否新增或者修改---做记录
     * */
    private function _model_down_record_save_update($data){
		$shop_id=$data['shop_id'];
		$card_no=$data['card_no'];
		$type=$data['type'];
		$model=db("ModelDownRecord")->where("card_no='$card_no' and shop_id=$shop_id and type=$type ")->field("id,card_no")->find();
		if(empty($model)){
			db("ModelDownRecord")->insert(array("card_no"=>$card_no,"shop_id"=>$shop_id,"type"=>$type,"is_down"=>0));
		}else{
			db("ModelDownRecord")->where("card_no='$card_no' and shop_id=$shop_id and type=$type")->update(array("is_down"=>0,"update_time"=>date("Y-m-d H:i:s")));
			$admin=session("Admin");
			db("FaceCodeRecord")->insert(array('shop_id'=>$data['shop_id'],'card_no'=>$data['card_no'],'name'=>input('name',""),'mobile'=>input('mobile'),'admin_account'=>$admin['account'],'admin_name'=>$admin['name'],'admin_mobile'=>$admin['mobile']));
		}
	}

    //插入或者修改facecode
    private function _face_code_insertOrupdate($data){
		if(empty($data)){
			return;
		}else{
			$card_no=$data["card_no"];
			$shop_id=$data['shop_id'];
			$model=db("FaceCode")->where(" card_no='$card_no' and shop_id=$shop_id")->find();
			if(empty($model)){//新增
				db("FaceCode")->insert(array('card_no'=>$data['card_no'],'face1'=>$data['face1'],'icon1'=>$data['icon1'],'shop_id'=>$data['shop_id']));
			}else{//修改
				db("FaceCode")->where("card_no='$card_no' and shop_id='$shop_id'")->update(array("face1"=>$data['face1'],"icon1"=>$data['icon1']));
			}
			$data['type']=2;
			$data['update_time']=date("Y-m-d H:i:s");
			$this->_model_down_record_save_update($data);
			return;
		}
	}

    //icon1 转arr
    private function getIcons($icon1){
        $icons=["/data/finger/a8.jpg","/data/finger/a8.jpg","/data/finger/a8.jpg"];
        foreach ($icon1 as $key => $value) {
            if (!empty($value)) {
                $icons[$key]=$value;
            }
        }
        return $icons;
    }
}